import React, { memo, useState, useEffect } from 'react';
import moment from 'moment';
import { createPortal } from 'react-dom';
import {
  Card,
  Button,
  Popup,
  NavBar,
  TextArea,
  Dialog,
  Toast,
  Ellipsis,
  SpinLoading,
} from 'antd-mobile';
import { InbizIcon, getCookie } from '@inbiz/utils';
import { useInbizRouter } from '@inbiz/hooks';
import Avatar from '../Avatar';
import { jumpTo } from '../utils';
import { goto, processState } from '../../commonUtils';
import { getvars } from '@components/form/process/ProcessButton/preview/commonUtils';
import { approval } from './service';
import { getProcessInfo } from '../service';
import { TextWidget, getMessage } from '@inbiz/react';
import _ from 'lodash';
import './index.less';

const ProcessApproval = memo((props: any) => {
  const list = localStorage.getItem('approvalList') as string;
  const [approvalList, $approvalList] = useState([]);
  const [visible, $visible] = useState(false);
  const [opinions, $opinions] = useState('');
  const [pageData, $pageData] = useState<any[]>([]);
  const [isApprove, $isApprove] = useState(false);
  const [loading, $loading] = useState(true);
  const router = useInbizRouter();
  const closePopup = () => {
    $visible(false);
    $opinions('');
  };
  const finallyfunction = (successNumber: any, failNumber: any) => {
    const fn = failNumber;
    if (fn == 0) {
      Toast.show({
        icon: 'success',
        content: getMessage('processCenter.approvalSuccess'),
      });
    } else {
      Toast.show({
        icon: 'fail',
        content: `${getMessage('processCenter.thereIs')}${fn}${getMessage(
          'processCenter.approvalDataFailed',
        )}`,
      });
    }
  };

  /**
   * 每一条数据都单独调接口保存, 统计成功的数据和失败的数据
   */
  const confirmed = () => {
    $loading(true);
    let newProcess = pageData?.filter((item1: any) => !item1?.queryData?.url);
    let oldProcess = pageData?.filter((item1: any) => item1?.queryData?.url);
    let newPromise: any[] = [];
    let oldPromise: any[] = [];
    if (!_.isEmpty(newProcess)) {
      newPromise = newProcess?.map((item: any) => {
        return () => {
          return new Promise(async (resolve, reject) => {
            try {
              let iframeWindow = document.getElementById(item?.taskId)?.contentWindow;
              let variablesParams = iframeWindow?.inbiz?.workFlow?.bpmnVarEntities;
              let params = {
                taskId: item?.taskId,
                comment: opinions,
                signDataStr: '',
                summary: iframeWindow?.inbiz('remark')?.value,
                variablesParams: '',
              };
              if (!_.isEmpty(variablesParams)) {
                iframeWindow?.inbiz
                  ?.submit()
                  .then(async (result: any) => {
                    const paramsValue = getvars(result.pageValue, iframeWindow?.inbiz, 'wap');
                    params.variablesParams = JSON.stringify(paramsValue);
                    const _result = await approval(params);
                    if (_result?.code == '200') {
                      resolve(true);
                    } else {
                      reject(false);
                    }
                  })
                  .catch((err) => {
                    $loading(false);
                    reject(false);
                  });
              } else {
                iframeWindow?.inbiz?.submit().then(async (result: any) => {
                  if (!result?.id) {
                    reject(false);
                  } else {
                    const _result = await approval(params);
                    if (_result?.code == '200') {
                      resolve(true);
                    } else {
                      reject(false);
                    }
                  }
                });
              }
            } catch (error) {
              reject(false);
            }
          });
        };
      });
    }

    if (!_.isEmpty(oldProcess)) {
      oldPromise = oldProcess?.map((item: any) => {
        return () => {
          return new Promise((resolve, reject) => {
            try {
              let iframeWindow = document.getElementById(item?.taskId)?.contentWindow;
              let textArea = iframeWindow.document
                .getElementsByClassName('edoc2workflowbutton')?.[0]
                .getElementsByTagName('textarea')[0];
              if (textArea) {
                textArea.value = opinions;
              }
              let _buttonsDom =
                iframeWindow?.document.getElementsByClassName('edoc2workflowbutton');
              let _length = _buttonsDom?.[0]?.childNodes.length;
              let unvaildChildNumber = 0;
              for (let i = 0; i < _length; i++) {
                if (_buttonsDom?.[0]?.childNodes[i]?.getAttribute('data-action') == 'approve') {
                  _buttonsDom?.[0]?.childNodes[i]?.click();
                } else {
                  unvaildChildNumber = unvaildChildNumber + 1;
                }
              }
              if (unvaildChildNumber == _length) {
                reject(false);
              }
              // let _confirmActions =
              //   iframeWindow?.document.getElementsByClassName('message-confirm-footer')[0];
              // _confirmActions?.childNodes[1]?.click();
              let controlWrapper = iframeWindow?.document.getElementsByClassName(
                'edoc2WorkFlowButtonContainer',
              )[0];
              let controlId = controlWrapper?.getAttribute('controlid');
              iframeWindow
                ?.eform(controlId)
                ?.method('afterSubmit', function (param: { result: boolean }) {
                  if (param.result === true) {
                    resolve(true);
                  } else {
                    reject(false);
                  }
                });
            } catch (error) {
              reject(false);
            }
          });
        };
      });
    }

    let promiseArray = newPromise?.concat(oldPromise);
    let successNumber = 0;
    let failureNumber = 0;

    for (let i = 0; i < promiseArray.length; i++) {
      promiseArray[i]?.()
        .then((res: boolean) => {
          if (res == true) {
            successNumber = successNumber + 1;
          }
        })
        .catch((err: boolean) => {
          if (err == false) {
            failureNumber = failureNumber + 1;
          }
        });
    }

    setTimeout(() => {
      let timer = setInterval(() => {
        if (successNumber + failureNumber == pageData?.length) {
          finallyfunction(successNumber, failureNumber);
          $loading(false);
          clearInterval(timer);
          router.goBack();
        }
      }, 100);
    }, 0);
  };

  /**
   * 移除数据
   */
  const removeItem = (item: { taskId: string }, e: React.MouseEvent) => {
    e.stopPropagation();
    Dialog.confirm({
      content: getMessage('processCenter.confirmToRemove'),
      confirmText: React.createElement(
        'span',
        { style: { color: 'var(--inbiz-color-primary)' } },
        getMessage('global.sure'),
      ),
      cancelText: React.createElement('span', {}, getMessage('global.cancel')),
      onConfirm: () => {
        let _approvalList = approvalList;
        _approvalList = _approvalList?.filter((ele: { taskId: string }) => item.taskId != ele.taskId);
        if (_approvalList?.length == 0) {
          $loading(true);
          Dialog.clear();
          setTimeout(() => {
            $loading(false);
            router.goBack();
          }, 300);
        };
        const _pageData = pageData?.filter((ele: { taskId: string }) => item.taskId != ele.taskId);
        $pageData(_pageData);
        $approvalList(_approvalList);
      },
    });
  };

  useEffect(() => {
    if (isApprove) {
      return () => {
        localStorage.setItem('approvalList', JSON.stringify([]));
        sessionStorage.removeItem('batchApproval');
      };
    }
  }, []);

  useEffect(() => {
    $loading(true);
    const newList = JSON.parse(list);
    const newArr: any[] = [];
    const oldArr: any[] = [];
    $approvalList(newList);

    const taskIds = newList.map((item) => item.taskId).join(',');
    let routeId = '';
    getProcessInfo({
      taskIds,
      inItiateApplication: false,
      siteType: 1,
    }).then((res) => {
      if (res.details && res.details.length > 0) {
        for (let index = 0; index < newList.length; index++) {
          const element = newList[index];
          const theDetails = res.details.find((item) => item.taskId == element.taskId);
          if (theDetails) {
            if (!theDetails.formId) {
              if (theDetails?.url) {
                routeId = theDetails?.url;
              }
              element.queryData = {
                id: theDetails.businessKey,
                taskId: theDetails.taskId,
                processId: theDetails.processDefinitionId,
                instanceId: theDetails.processInstanceId,
                pageVersion: theDetails.pageVersion,
                formId: theDetails.pageId,
                routeId,
                pageId: theDetails.pageId,
                siteDomName: theDetails.siteDomName,
              };
              newArr.push(element);
            } else if (theDetails.formId) {
              oldArr.push({
                ...element,
                queryData: {
                  ...theDetails,
                },
              });
            }
          }
        }
        $pageData(newArr.concat(oldArr));
      } else {
        $loading(false);
        Toast.show({
          icon: 'fail',
          content: res?.message || '',
        });
        router.goBack();
      }
    });
  }, [list]);

  useEffect(() => {
    if (pageData?.length) {
      let newProcess = pageData?.filter((item: any) => !item?.queryData?.url);
      let oldProcess = pageData?.filter((item: any) => item?.queryData?.url);
      let taskIds = pageData?.map((item: any) => item?.taskId);
      let _approvalList = approvalList?.filter((item: any) => taskIds?.includes(item?.taskId));
      $approvalList(_approvalList);
      let newPromise: any[] = [];
      let oldPromise: any[] = [];
      if (!_.isEmpty(newProcess)) {
        newPromise = newProcess?.map((item: any) => {
          return () => {
            return new Promise((resolve, reject) => {
              let timer = setInterval(() => {
                let iframeWindow = document.getElementById(item?.taskId)?.contentWindow;
                if (iframeWindow?.inbiz) {
                  resolve(true);
                  clearInterval(timer);
                }
              }, 100);
            });
          };
        });
      }

      if (!_.isEmpty(oldProcess)) {
        oldPromise = oldProcess?.map((item: any) => {
          return () => {
            return new Promise((resolve, reject) => {
              let timer = setInterval(() => {
                let iframeWindow = document.getElementById(item?.taskId)?.contentWindow;
                if (iframeWindow?.eform?.formEngine?.isLoaded) {
                  resolve(true);
                  clearInterval(timer);
                }
              }, 100);
            });
          };
        });
      }

      let promiseArray = newPromise?.concat(oldPromise);
      let successNumber = 0;
      let failureNumber = 0;

      for (let i = 0; i < promiseArray.length; i++) {
        promiseArray[i]?.()
          .then((res: boolean) => {
            if (res == true) {
              successNumber = successNumber + 1;
            }
          })
          .catch((err: boolean) => {
            if (err == false) {
              failureNumber = failureNumber + 1;
            }
          });
      }

      setTimeout(() => {
        let timer1 = setInterval(() => {
          if (pageData?.length == successNumber + failureNumber) {
            $loading(false);
            clearInterval(timer1);
          }
        }, 100);
      }, 0);
    }
  }, [pageData]);

  return createPortal(
    <div className={'processApproval'}>
      {loading && (
        <div className={'loading'}>
          <SpinLoading />
        </div>
      )}
      {approvalList.map((item: any, index: number) => {
        return (
          <Card
            className={'approvalContainer'}
            title={
              <div>
                {item.processName}{' '}
                <span
                  className={'cardTitle'}
                  style={{
                    background: processState[item.taskState].stateBgColor,
                    color: processState[item.taskState].stateFontColor,
                  }}
                >
                  <TextWidget>{processState[item.taskState].stateName}</TextWidget>
                </span>
              </div>
            }
            extra={
              <InbizIcon
                type="icon-shanchu-h"
                style={{ color: '#9b9b9b', fontSize: 16 }}
                onClick={(e) => removeItem(item, e)}
              />
            }
            key={index}
          >
            <header
              className={'cardHeader'}
              onClick={(e) => {
                sessionStorage.setItem('batchApproval', 'true');
                goto(
                  {
                    processInstanceId: item.processInstanceId,
                    starter: item.taskAssignee,
                    taskIds: item.taskId,
                    taskState: item.taskState,
                    siteType: 1,
                  },
                  '9',
                  'wap',
                  e,
                  1,
                );
              }}
            >
              <Avatar userId={item.userId} style={{ width: 40, height: 40 }} />
              <p>
                <h4 className={'userName'} title={item.initiatorName}>
                  {' '}
                  {item.initiatorName}
                </h4>
                {
                  typeof item.summary === 'string' && item.summary.trim() !== '' &&
                  <p className={'summary'} title={item.summary}>
                    <Ellipsis direction="end" rows={2} content={item.summary} />
                  </p>
                }
              </p>
            </header>
            <section
              className={'cardBody'}
              onClick={(e) => {
                sessionStorage.setItem('batchApproval', 'true');
                goto(
                  {
                    processInstanceId: item.processInstanceId,
                    starter: item.taskAssignee,
                    taskIds: item.taskId,
                    taskState: item.taskState,
                    siteType: 1,
                  },
                  '9',
                  'wap',
                  e,
                  1,
                );
              }}
            >
              <p>
                <TextWidget>processCenter.instanceNumber</TextWidget>: {item.processInstanceId}
              </p>
              <p>{moment(item.taskCreateTime).format('YYYY-MM-DD HH:mm:ss')}</p>
            </section>
            <section className={'cardFooter'}>
              <p
                style={{ color: 'var(--inbiz-color-primary)' }}
                onClick={() => {
                  jumpTo(item, router);
                  $isApprove(true);
                }}
              >
                <InbizIcon
                  type="icon-process-liuchengrizhi"
                  style={{ color: 'var(--inbiz-color-primary)', fontSize: 12 }}
                />
                <span style={{ marginLeft: 5 }}>
                  <TextWidget>processCenter.processLog</TextWidget>
                </span>
              </p>
              <p
                onClick={(e) => {
                  sessionStorage.setItem('batchApproval', 'true');
                  goto(
                    {
                      processInstanceId: item.processInstanceId,
                      starter: item.taskAssignee,
                      taskIds: item.taskId,
                      taskState: item.taskState,
                      siteType: 1,
                    },
                    '9',
                    'wap',
                    e,
                    1,
                  );
                }}
              >
                <TextWidget>processCenter.lookDetails</TextWidget>
              </p>
            </section>
          </Card>
        );
      })}
      <div style={{ display: 'none' }} className="test9999">
        {pageData.map((item: any, index) => {
          let _url = !item?.queryData?.url
            ? `${location.origin}${process.env.NODE_ENV == 'development' ? '' : '/inbiz/wap'}/${item?.queryData?.siteDomName
            }?dataVersionId=${item?.queryData?.pageVersion || ''}#${process.env.NODE_ENV == 'development' ? '/preview/page' : '/page'
            }${item?.queryData?.routeId}?id=${item?.queryData?.id}&taskId=${item?.queryData?.taskId
            }&processId=${item?.queryData?.processId}&instanceId=${item?.queryData?.instanceId
            }&formId=${item?.queryData?.formId}&tabKey=2&drafID=&taskState=0&pageId=${item?.queryData?.pageId
            }`
            : `${item?.queryData?.url}?formId=${item?.queryData?.formId
            }&skin=lighttechblue&processId=${item?.queryData?.processId
            }&taskType=inboxtask&taskId=${item?.queryData?.taskId}&id=${item?.queryData?.businessKey
            }&incidentId=${item?.queryData?.processInstanceId}&token=${getCookie(
              'token',
            )}&isArchiveTask=false&taskState=0&formver=${item?.queryData?.formver
            }&ishide=true&islog=true&isPop=true`;
          return <iframe id={item.taskId} src={_url} />;
        })}
      </div>
      <div className={'approvalFooter'}>
        {!loading && (
          <Button color="primary" onClick={() => $visible(true)} block>
            <TextWidget>processCenter.agree</TextWidget>
          </Button>
        )}
        <Popup
          visible={visible}
          onMaskClick={() => closePopup()}
          position="bottom"
          bodyClassName={'process-center-approval-all-popup'}
        >
          <>
            <header className={'popupHeader'}>
              <NavBar
                onBack={() => closePopup()}
                backArrow={
                  <a style={{ fontSize: 16 }}>
                    <TextWidget>global.cancel</TextWidget>
                  </a>
                }
              />
            </header>
            <section style={{ padding: '0 12px' }}>
              <h4>
                <TextWidget>processCenter.comment</TextWidget>
              </h4>
              <TextArea
                value={opinions}
                rows={5}
                placeholder={getMessage('processCenter.inputComment')}
                onChange={(val) => {
                  if(val && val?.length > 163){
                    Toast.show({
                      icon: 'fail',
                      content: getMessage('processCenter.tooManyComment'),
                    });
                    return;
                  }
                  $opinions(val)
                }}
              />
            </section>
            <footer className={'popoupFooter'}>
              <Button
                block
                style={{ height: 40, backgroundColor: 'var(--inbiz-color-primary)', color: '#fff' }}
                onClick={confirmed}
                loading={loading}
              >
                <TextWidget>processCenter.confirm</TextWidget>
              </Button>
            </footer>
          </>
        </Popup>
      </div>
    </div>,
    document.querySelector('body') as Element,
  );
});

export default ProcessApproval;
